package com.mdxl.third.controller;

import com.alibaba.fastjson.JSONObject;
import com.mdxl.second.Entity.AdminEntity;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.mapreduce.GroupBy;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;

@Controller
@RequestMapping(value = "/third")
public class Thrid {
    private  Logger logger = LoggerFactory.getLogger(Thrid.class);

    @Autowired
    MongoTemplate mongoTemplate;

    /*
    * or查询 orOperator
    * 更新集合中的数据的信息 updateMulti(new Query()..,new Update()..,*.class)
    * 对查询结果排序 query.sort().on("",)  query.sort().on("time", Order.DESCENDING);
    * 分页查询 skip(2).limit(3)
    * 指定查询字段 query.fields().include("name").include("sex");
    *
    * */
    @RequestMapping(value = "/get",method = RequestMethod.GET)
    @ResponseBody
    public String get(){
        String account ="cj";
        AdminEntity adminEntity =mongoTemplate.findOne(new Query(Criteria.where("account").is(account).and("nickName").is("chengjian")), AdminEntity.class);
        return adminEntity.toString();
    }

    //写一个查询排序分页带分组
    @RequestMapping(value = "/sortAndGroup",method = RequestMethod.GET)
    @ResponseBody
    public String sortAndGroup(){
        //添加查询条件，手机号在100到90000之间
        Criteria criteria =Criteria.where("mobile").gte("100").lte("90000");
        Aggregation aggregation =Aggregation.newAggregation(
                //project("nickName","account"),
               // match(criteria),
                group("nickName").count().as("num")
                //对字段nickName分组，并计算每一组的总数量，返回结果就是两列，一个是nickName的种类值，另外一个是该值得总数量
        );
        AggregationResults<AdminEntity> aggregate=mongoTemplate.aggregate(aggregation,"adminEntity",AdminEntity.class);
        BasicDBList basicDBList = (BasicDBList) aggregate.getRawResults().get("result");
        List<JSONObject> jsonObjects =new ArrayList<>();
        for (int i =0;i<basicDBList.size();i++){
            BasicDBObject basicDBObject = (BasicDBObject) basicDBList.get(i);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(String.valueOf(basicDBObject));
            jsonObjects.add(jsonObject);
        }
        return jsonObjects.toString();
    }
    //添加
    @RequestMapping(value = "/insert",method = RequestMethod.GET)
    @ResponseBody
    public String add(){
        for (int i=0;i<30;i++) {
            AdminEntity adminEntity = new AdminEntity();
            adminEntity.setId(UUID.randomUUID().toString());
            adminEntity.setNickName("76521");
            adminEntity.setStatus(2);
            adminEntity.setPassword("77523");
            String a = String.valueOf(new Random().nextInt(60) * 36);
            adminEntity.setMobile("" + a);
            mongoTemplate.insert(adminEntity);
        }
        return "OK";
    }
    @RequestMapping(value = "/groupBy",method = RequestMethod.GET)
    @ResponseBody
    public String groupby(){
        //分组条件
        GroupBy groupBy =new GroupBy("nickName")
                .initialDocument("{conut:0}")
                .reduceFunction("function (doc,pre){pre.count +=1 ;}");

        GroupByResults<AdminEntity> results =mongoTemplate.group("adminEntity",groupBy,AdminEntity.class);
        BasicDBList basicDBList = (BasicDBList) results.getRawResults().get("retval");
        List<JSONObject> lists =null;
        JSONObject obj =null;
        for (Object item : basicDBList){
            obj = JSONObject.parseObject(item.toString());
            lists.add(obj);
        }
        return lists.toString();
   }
}
